package cn.it.shop.lucene;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.search.IndexSearcher;
import org.springframework.stereotype.Component;

/*
 * 用来封装 Wirter Seach
 * */
@Component("luceneUtil")
public class LuceneUtil {
	@Resource
	private Configuraction configuraction;

	private IndexWriter indexWriter;
	// 每次创建的的时候Term集合,都会加载到内存中
	private IndexSearcher indexSearcher;

	@PostConstruct
	public void init() {
		try {
			indexWriter = new IndexWriter(configuraction.getDirectory(),
					configuraction.getAnalyzer(), MaxFieldLength.LIMITED);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	// Bean对象销毁之前执行
	@PreDestroy
	public void destory(){
		System.out.println("------destory()-------");
		try {
			indexWriter.close();
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public IndexWriter getIndexWriter() {
		if(indexSearcher!=null){
			try {
				indexSearcher.close();
				indexSearcher=null;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return indexWriter;
	}

	public IndexSearcher getIndexSearcher() {
		// 避免线程堵塞
		if(indexSearcher==null){
			synchronized(LuceneUtil.class){
				// 避免重复创建
				if(indexSearcher==null){
					try {
						indexSearcher=new IndexSearcher(configuraction.getDirectory());
					}catch (Exception e) {
						throw new RuntimeException(e);
					}
				}
			}
		}
		return indexSearcher;
	}
}
